﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;

namespace WebLib
{
    public class WebHelper
    {
        public static string GetClientUserIP()
        {
            var visitorsIPAddr = string.Empty;

            if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
            {
                visitorsIPAddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            }
            else if (!string.IsNullOrEmpty(HttpContext.Current.Request.UserHostAddress))
            {
                visitorsIPAddr = HttpContext.Current.Request.UserHostAddress;
            }

            return visitorsIPAddr;
        }

        public static string StripTagsCharArray(string source)
        {
            if (string.IsNullOrEmpty(source)) return string.Empty;

            var array = new char[source.Length];
            var arrayIndex = 0;
            var inside = false;

            foreach (var let in source)
            {
                if (let == '<')
                {
                    inside = true;
                    continue;
                }
                if (let == '>')
                {
                    inside = false;
                    continue;
                }

                if (inside) continue;

                array[arrayIndex] = @let;
                arrayIndex++;
            }
            var returnText = new string(array, 0, arrayIndex);

            return string.IsNullOrEmpty(returnText) ? string.Empty : returnText.Replace("&nbsp;", "");
        }

        public static string GetImageUrlFromHtml(string html)
        {
            var regexPattern = @"<[Ii][Mm][Gg][^>]*src\s*=\s*[\""\']?(?<IMAGE_URL>[^""'>\s]*)[\""\']?[^>]*>";
            
            var m = Regex.Match(html, regexPattern);

            return m.Groups["IMAGE_URL"].ToString();

        }
    }
}
